#! /usr/bin/env python
# -*- coding:utf-8 -*-
from aliyunsdkcore.client import AcsClient
from aliyunsdkalidns.request.v20150109.DescribeDomainRecordsRequest import DescribeDomainRecordsRequest
from aliyunsdkalidns.request.v20150109.UpdateDomainRecordRequest import UpdateDomainRecordRequest
import json
import sys
import urllib
from bs4 import BeautifulSoup

# 一级域名
dommainName = ''
# 域名前缀
dommainRR = ''
accessKeyId = ''
accessSecret = ''


def getPublicNetwork():
    result = urllib.urlopen('http://ip.tool.chinaz.com/').read()
    html = BeautifulSoup(result, 'html.parser')
    tag = html.find('dd', {'class', 'fz24'})
    return tag.get_text()


def findDommain():
    reload(sys)
    sys.setdefaultencoding('utf-8')
    client = AcsClient(accessKeyId, accessSecret, 'cn-hangzhou')
    request = DescribeDomainRecordsRequest()
    request.set_DomainName(dommainName)
    request.set_RRKeyWord(dommainRR)
    response = client.do_action_with_exception(request)
    response = json.loads(response)
    recordId = ''
    for var in response['DomainRecords']['Record']:
        if var['RR'] == dommainRR:
            if var['Value'] == getPublicNetwork():
                print ('域名没有变化无需更改')
                return
            recordId = var['RecordId']
            break
    print('获取域名RecordId' + recordId)
    request = UpdateDomainRecordRequest()
    request.set_accept_format('json')
    request.set_RR(dommainRR)
    request.set_RecordId(recordId)
    request.set_Type('A')
    request.set_Value(getPublicNetwork())
    response = client.do_action_with_exception(request)
    print (str(response))


if __name__ == '__main__':
    findDommain()
